import express from 'express';
import { param, validationResult } from 'express-validator';
import { Expert, Domain, Question, User, UserQuota } from '../models/index.js';
import { catchAsync } from '../utils/catchAsync.js';
import { NotFoundError } from '../utils/errors.js';
import { processExpertImageUrls } from '../utils/imageUrl.js';

const router = express.Router();

// 渲染函数
const renderWithLayout = (res, template, data, title, description) => {
  res.render('preview/layout', {
    title,
    description,
    body: res.render(`preview/${template}`, data, (err, html) => {
      if (err) throw err;
      return html;
    })
  });
};

// 在所有预览路由之前添加CSP中间件
router.use((req, res, next) => {
  // 移除helmet设置的CSP头
  res.removeHeader('Content-Security-Policy');
  
  // 设置预览页面专用的宽松CSP
  res.setHeader('Content-Security-Policy', 
    "default-src 'self'; " +
    "script-src 'self' 'unsafe-inline' https:; " +
    "style-src 'self' 'unsafe-inline' https:; " +
    "img-src 'self' data: https:; " +
    "connect-src 'self' https: http:; " +
    "font-src 'self' https:; " +
    "object-src 'none'; " +
    "media-src 'self'; " +
    "frame-src 'none';"
  );
  
  next();
});

// 预览首页
router.get('/', catchAsync(async (req, res) => {
  res.render('preview/layout', {
    title: '数据预览',
    description: '彼知AI数据预览页面',
    body: await new Promise((resolve, reject) => {
      res.render('preview/index', {}, (err, html) => {
        if (err) reject(err);
        else resolve(html);
      });
    })
  });
}));

// 登录测试页面
router.get('/login-test', catchAsync(async (req, res) => {
  res.render('preview/layout', {
    title: '用户登录测试',
    description: '用户手机验证码登录功能测试页面',
    body: await new Promise((resolve, reject) => {
      res.render('preview/login-test', {}, (err, html) => {
        if (err) reject(err);
        else resolve(html);
      });
    })
  });
}));

// 专家详情预览
router.get('/expert/:id',
  [
    param('id').isInt({ min: 1 }).withMessage('专家ID必须是正整数')
  ],
  catchAsync(async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).render('preview/layout', {
        title: '参数错误',
        description: '专家ID参数无效',
        body: `
          <div class="error">
            <h2>参数错误</h2>
            <p>专家ID必须是正整数</p>
            <a href="/preview" class="btn">返回首页</a>
          </div>
        `
      });
    }

    const { id } = req.params;
    
    try {
      // 直接查询数据库获取专家信息
      const expert = await Expert.findByPk(id, {
        include: [
          {
            model: Domain,
            as: 'domain',
            attributes: ['id', 'name', 'description', 'welcome_message_1', 'welcome_message_2', 'precondition_config']
          }
        ]
      });

      if (!expert) {
        return res.status(404).render('preview/layout', {
          title: '专家不存在',
          description: '找不到指定的专家',
          body: `
            <div class="error">
              <h2>专家不存在</h2>
              <p>找不到ID为 ${id} 的专家</p>
              <a href="/preview" class="btn">返回首页</a>
            </div>
          `
        });
      }

      // 如果专家未启用，显示提示信息
      if (!expert.is_enabled) {
        return res.status(404).render('preview/layout', {
          title: '专家未启用',
          description: '该专家当前未启用',
          body: `
            <div class="error">
              <h2>专家未启用</h2>
              <p>专家 "${expert.nickname}" 当前未启用</p>
              <a href="/preview" class="btn">返回首页</a>
            </div>
          `
        });
      }

      // 处理专家数据中的图片URL
      const processedExpert = await processExpertImageUrls(expert.toJSON());

      // 渲染专家详情页面
      res.render('preview/layout', {
        title: `${expert.nickname} - 专家详情`,
        description: expert.bio || `${expert.nickname}专家详情页面`,
        body: await new Promise((resolve, reject) => {
          res.render('preview/expert', { expert: processedExpert }, (err, html) => {
            if (err) reject(err);
            else resolve(html);
          });
        })
      });

    } catch (error) {
      console.error('获取专家详情失败:', error);
      res.status(500).render('preview/layout', {
        title: '服务器错误',
        description: '获取专家详情时发生错误',
        body: `
          <div class="error">
            <h2>服务器错误</h2>
            <p>获取专家详情时发生错误，请稍后再试</p>
            <a href="/preview" class="btn">返回首页</a>
          </div>
        `
      });
    }
  })
);

// 问答详情预览
router.get('/question/:id',
  [
    param('id').isInt({ min: 1 }).withMessage('问答ID必须是正整数')
  ],
  catchAsync(async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).render('preview/layout', {
        title: '参数错误',
        description: '问答ID参数无效',
        body: `
          <div class="error">
            <h2>参数错误</h2>
            <p>问答ID必须是正整数</p>
            <a href="/preview" class="btn">返回首页</a>
          </div>
        `
      });
    }

    const { id } = req.params;
    
    try {
      // 直接查询数据库获取问答信息
      const question = await Question.findByPk(id, {
        include: [
          {
            model: Expert,
            as: 'expert',
            attributes: ['id', 'nickname', 'avatar_url', 'bio'],
            include: [
              {
                model: Domain,
                as: 'domain',
                attributes: ['id', 'name']
              }
            ]
          },
          {
            model: User,
            as: 'user',
            attributes: ['id', 'phone', 'nickname']
          },
          {
            model: UserQuota,
            as: 'quota',
            attributes: ['id', 'quota_type']
          }
        ]
      });

      if (!question) {
        return res.status(404).render('preview/layout', {
          title: '问答不存在',
          description: '找不到指定的问答',
          body: `
            <div class="error">
              <h2>问答不存在</h2>
              <p>找不到ID为 ${id} 的问答</p>
              <a href="/preview" class="btn">返回首页</a>
            </div>
          `
        });
      }

      // 渲染问答详情页面
      res.render('preview/layout', {
        title: `问答详情 #${question.id}`,
        description: question.question ? question.question.substring(0, 100) + '...' : '问答详情页面',
        body: await new Promise((resolve, reject) => {
          res.render('preview/question', {
            question,
            getStatusType: (status) => {
              switch (status) {
                case 'pending': return 'warning';
                case 'answered': return 'success';
                case 'failed': return 'error';
                default: return 'primary';
              }
            },
            getStatusText: (status) => {
              switch (status) {
                case 'pending': return '处理中';
                case 'answered': return '已回答';
                case 'failed': return '回答失败';
                default: return '未知状态';
              }
            },
            getRatingText: (rating) => {
              const ratingTexts = {
                1: '很不满意',
                2: '不满意',
                3: '一般',
                4: '满意',
                5: '很满意'
              };
              return `${rating}分 (${ratingTexts[rating] || '未知'})`;
            }
          }, (err, html) => {
            if (err) reject(err);
            else resolve(html);
          });
        })
      });

    } catch (error) {
      console.error('获取问答详情失败:', error);
      res.status(500).render('preview/layout', {
        title: '服务器错误',
        description: '获取问答详情时发生错误',
        body: `
          <div class="error">
            <h2>服务器错误</h2>
            <p>获取问答详情时发生错误，请稍后再试</p>
            <a href="/preview" class="btn">返回首页</a>
          </div>
        `
      });
    }
  })
);

// API测试页面
router.get('/api-test', catchAsync(async (req, res) => {
  res.render('preview/api-test');
}));

export default router;
